package com.framework.loippi.envsupport;

import com.framework.loippi.support.APIPrincipal;
import com.framework.loippi.utils.IPAddrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@WebFilter(filterName = "envInitFilter", urlPatterns = "/*")
public class EnvInitFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(EnvInitFilter.class);
    private static Set<String> urlPatterns = new HashSet<>();

    static {
        urlPatterns.add(".eot");
        urlPatterns.add(".ttf");
        urlPatterns.add(".css");
        urlPatterns.add(".xml");
        urlPatterns.add(".swf");
        urlPatterns.add(".zip");
        urlPatterns.add(".rar");
        urlPatterns.add(".pdf");
        urlPatterns.add(".doc");
        urlPatterns.add(".docx");
        urlPatterns.add(".xls");
        urlPatterns.add(".xlsx");
        urlPatterns.add(".gif");
        urlPatterns.add(".png");
        urlPatterns.add(".jpg");
        urlPatterns.add(".js");
        urlPatterns.add(".html");
        urlPatterns.add(".woff");
        urlPatterns.add(".txt");
    }

    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        if (!isStaticResource(httpServletRequest)) {

            UserEnvInfo userEnvInfo = EnvManager.getUserEnvInfo();
            String sessionId = httpServletRequest.getSession().getId();

            String ipAddress = IPAddrUtils.try2GetUserRealIPAddr(httpServletRequest);
            if (ipAddress != null) {
                EnvManager.putEnvParam(EnvParam.CLIENT_IP.name(), ipAddress);
                EnvManager.putEnvParam("clientIp", ipAddress);
                userEnvInfo.setClientIp(ipAddress);
            }

            if (sessionId != null) {
                EnvManager.putEnvParam(EnvParam.SESSION_ID.name(), sessionId);
                userEnvInfo.setSessionId(sessionId);
            }

            String userAgent = httpServletRequest.getHeader("User-Agent");
            if (userAgent != null) {
                EnvManager.putEnvParam(EnvParam.USER_AGENT.name(), userAgent);
                userEnvInfo.setUserAgent(userAgent);
            }

            String host = httpServletRequest.getHeader("Host");
            if (host != null) {
                EnvManager.putEnvParam(EnvParam.DOMAIN.name(), host);
                userEnvInfo.setDomain(host);
            }

            String token = httpServletRequest.getParameter(APIPrincipal.PORPERTITY_AUTHENTICATION);
            if (token == null) {
                token = httpServletRequest.getHeader(APIPrincipal.PORPERTITY_AUTHENTICATION);
            }
            if (token != null) {
                EnvManager.putEnvParam(EnvParam.TOKEN.name(), token);
                userEnvInfo.setToken(token);
            }

            if (sessionId != null && !sessionId.equals(userEnvInfo.getSessionId())) {
                logger.debug("用户环境参数->" + userEnvInfo);
            }
        }

        chain.doFilter(request, response);
    }

    private boolean isStaticResource(HttpServletRequest request) {
        String requestURI = request.getRequestURI();

        for (String urlPattern : urlPatterns) {
            if (requestURI.endsWith(urlPattern)) {
                return true;
            }
        }
        return false;
    }


    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
